package com.loren.demo20.repository;

import com.loren.demo20.entity.User;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@Repository
public class UserRepository {

    private static final List<User> USERS = new ArrayList<>(Collections.singletonList(new User(1L, "loren", "123456")));

    public User findOne(long id) {
        System.out.println("...call UserRepository.findOne...");
        return USERS.stream().filter(user -> user.getId() == id).findFirst().orElse(null);
    }

    public long save(User user) {
        System.out.println("...call UserRepository.save...");
        List<Long> userIds = USERS.stream()
                .map(User::getId)
                .sorted()
                .collect(Collectors.toList());
        Long userId = user.getId();
        if (userId == null) {
            userId = userIds.get(userIds.size() - 1) + 1;
        } else {
            if (userIds.contains(user.getId())) {
                throw new RuntimeException("Duplicate primary key " + user.getId());
            }
        }
        user.setId(userId);
        USERS.add(user);
        return userId;
    }

    public void update(User user) {
        System.out.println("...call UserRepository.user...");
        if (user.getId() == null) {
            throw new RuntimeException("User primary key is null");
        }
        User disk = this.findOne(user.getId());
        if (disk == null) {
            throw new RuntimeException("Can not find the user info, primary key " + user.getId());
        }
        disk.setUsername(user.getUsername());
        disk.setPassword(user.getPassword());
    }
}
